package com.gitee.huanminabc.dynamicdb.common;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Map;
/**
 * @author huanmin
 * @date 2024/11/22
 */
public class AutoBeanInject {
    public static void addBeanField(String beanName, Class clazz, Map<String, Object> basics, Map<String, String> quote) {
        //将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) SpringContextHolder.getApplicationContext();

        // 获取bean工厂并转换为DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();

        // 通过BeanDefinitionBuilder创建bean定义
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);


        if (basics!=null) {
            //给基本数据类型赋值
            for (Map.Entry<String, Object> stringObjectEntry : basics.entrySet()) {
                beanDefinitionBuilder.addPropertyValue(stringObjectEntry.getKey(), stringObjectEntry.getValue());
            }
        }
        if (quote!=null) {
            //将容器中的指定bean注入到当前类的指定属性对象上
            for (Map.Entry<String, String> stringObjectEntry : quote.entrySet()) {
                //如果指定了属性值设置为Autowired   那么就自动装配(从容器中选取一个这个属性对象的子类或者实现类来装配)
                if ("Autowired".equals(stringObjectEntry.getValue())) {
                    beanDefinitionBuilder.addAutowiredProperty(stringObjectEntry.getKey());
                }
                beanDefinitionBuilder.addPropertyReference(stringObjectEntry.getKey(), stringObjectEntry.getValue());
            }
        }
        // 注册bean   将 beanName 注册到容器里了
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());

    }
}
